/**
 * MenuSubItem
 * @authors 杨兴洲（of2502）
 * @date    2017/6/2 0002 11:52
 * @version 1.0
 * @last-modify  杨兴洲（of2502）
 */

import React, {Component} from 'react';
import {findDOMNode} from 'react-dom';
import {Map, List, fromJS} from 'immutable'
import {DragSource, DropTarget} from 'react-dnd';
import GaUtil from "util/ga-util";

const cardSource = {
    beginDrag(props) {
        return {
            id: props.key,
            index: props.index,
        };
    },
};

const cardTarget = {
    hover(props, monitor, component) {
        const dragIndex = monitor.getItem().index;
        const hoverIndex = props.index;

        // Don't replace items with themselves
        if (dragIndex === hoverIndex) {
            return;
        }

        // Determine rectangle on screen
        const hoverBoundingRect = findDOMNode(component).getBoundingClientRect();

        // Get vertical middle
        const hoverMiddleY = (hoverBoundingRect.bottom - hoverBoundingRect.top) / 2;

        // Determine mouse position
        const clientOffset = monitor.getClientOffset();

        // Get pixels to the top
        const hoverClientY = clientOffset.y - hoverBoundingRect.top;

        // Only perform the move when the mouse has crossed half of the items height
        // When dragging downwards, only move when the cursor is below 50%
        // When dragging upwards, only move when the cursor is above 50%

        // Dragging downwards
        if (dragIndex < hoverIndex && hoverClientY < hoverMiddleY) {
            return;
        }

        // Dragging upwards
        if (dragIndex > hoverIndex && hoverClientY > hoverMiddleY) {
            return;
        }

        // Time to actually perform the action
        props.moveSubItem(dragIndex, hoverIndex);
        GaUtil.addEvent({eventAction: "子菜单排序", eventLabel: "自定义菜单"})
        // Note: we're mutating the monitor item here!
        // Generally it's better to avoid mutations,
        // but it's good here for the sake of performance
        // to avoid expensive index searches.
        monitor.getItem().index = hoverIndex;
    },
};


@DropTarget("SUB_ITEM", cardTarget, connect => ({
    connectDropTarget: connect.dropTarget(),
}))
@DragSource("SUB_ITEM", cardSource, (connect, monitor) => ({
    connectDragSource: connect.dragSource(),
    isDragging: monitor.isDragging(),
}))
export default class MenuSubItem extends Component {
    render() {
        const {selectSubItem, isActive, data, connectDragSource, connectDropTarget, isDragging} = this.props;
        const {name, type} = data;
        return connectDragSource(connectDropTarget(
            <li onClick={(e) => {
                e.stopPropagation();
                selectSubItem();
            }}
                className={`menu-sub-button ${isActive ? "active" : ""} ${isDragging ? "dragging" : ""}`}>
                {name}
            </li>
        ));
    }
}